package com.example.login;

import com.example.domain.User;
import com.example.utils.Utils;
import org.apache.commons.dbutils.QueryRunner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author mucd
 * 2021年06月22日  18:23
 */

@WebServlet(value = "/Register")
public class Register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("rname");
        String password = req.getParameter("rpasswd");
        String code = req.getParameter("code");

        System.out.println("验证码:" + req.getSession().getAttribute("vcode"));

        //跳转到登录

        //判断验证码是否正确
        String vcode = (String) req.getSession().getAttribute("vcode");
        if (code.equalsIgnoreCase(vcode)) {
            if (addUser(username, password) > 0) {
                req.setAttribute("cg",true);
                req.getRequestDispatcher("register.jsp").forward(req,resp);
            } else {
                req.getSession().setAttribute("text", "注册失败重新<a href='register.jsp'>注册</a>");
                resp.sendRedirect("fail.jsp");
            }
        } else {
//            <a href='register.jsp'>注册</a>
            req.getSession().setAttribute("text", "验证码错误重新输入");
            req.getRequestDispatcher("register.jsp").forward(req,resp);
        }

    }

    /**
     * 添加账号
     */
    int userNum;

    private int addUser(String user, String passwd) {
        User u = new User();
        u.setUser(user);
        u.setPassword(passwd);
        QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());
        try {
            int update = queryRunner.update(
                    "insert into web.username (user,password) values(?,?)"
                    , u.getUser(),u.getPassword()
            );
            if (update > 0) {
                userNum++;
            }
            System.out.println("共添加了" + userNum + "位用户");
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}